package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.ExecutionWashing;
import net.hn.hnms.biz.plan.mapper.ExecutionWashingMapper;
import net.hn.hnms.biz.plan.request.ExecutionWashingReq;
import net.hn.hnms.biz.plan.service.IExecutionWashingService;
import net.hn.hnms.biz.plan.vo.ExecutionWashingVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.common.satoken.utils.LoginHelper;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 洗选计划管理服务层实现
 * @date 2022-08-01
 */

@Service
@DS("master")
public class ExecutionWashingServiceImpl extends BaseService<ExecutionWashing, ExecutionWashingVO> implements IExecutionWashingService {

    @Autowired
    private ExecutionWashingMapper executionWashingMapper;
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * @param executionWashing
     * @param pageQuery       查询洗选计划列表
     */
    @Override
    public ResponsePage<ExecutionWashingVO> selectPageList(ExecutionWashingReq executionWashing, PageQuery pageQuery) {

        Page<ExecutionWashing> page = executionWashingMapper.selectPage(pageQuery.build(), buildQuery(executionWashing).orderByDesc(ExecutionWashing::getExecutionDate).orderByDesc(ExecutionWashing::getCreateTime));
        List<ExecutionWashingVO> list =page.getRecords().stream().map(o ->convert(o, ExecutionWashingVO.class)).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });
        return new ResponsePage<>(list, page.getTotal());
    }


    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<ExecutionWashing> 查询条件
     */
    private LambdaQueryWrapper<ExecutionWashing> buildQuery(ExecutionWashingReq req){
        LambdaQueryWrapper<ExecutionWashing> lqw = new LambdaQueryWrapper<ExecutionWashing>()
                .eq(StrUtil.isNotBlank(req.getShiftId()), ExecutionWashing::getShiftId, req.getShiftId())
//                .eq(StrUtil.isNotBlank(req.getMineCode()), ExecutionWashing::getMineCode, req.getMineCode())
                .ge(req.getBeginDateTime() != null, ExecutionWashing::getExecutionDate, req.getBeginDateTime())
                .le(req.getEndDateTime() != null, ExecutionWashing::getExecutionDate, req.getEndDateTime())
                .and(o->o.eq(req.getMineCode()!=null, ExecutionWashing::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, ExecutionWashing::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }

    /**
     *
     * @param executionWashing
     * 查询带值班人员列表
     */
    @Override
    public List<ExecutionWashingVO> selectList(ExecutionWashingReq executionWashing) {
        List<ExecutionWashing> list = executionWashingMapper.selectList(buildQuery(executionWashing));
        return list.stream().map(o ->  convert(o, ExecutionWashingVO.class)).collect(Collectors.toList());
    }

    /**
     * @param executionWashing 新增洗选计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ExecutionWashingReq executionWashing) {
//        QueryWrapper<ExecutionWashing> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("development_plan_code", executionWashing.getExecutionWashingCode());
//        if (executionWashingMapper.selectCount(queryWrapper) > 0) {
//            throw new HuaNengException(Constants.FAIL, "已存在相同的计划编号");
//        }
        ExecutionWashing insertObj = new ExecutionWashing();
        BeanUtil.copyProperties(executionWashing, insertObj);
        int insert = executionWashingMapper.insert(insertObj);
        return insert;
    }

    /**
     * @param idList 批量删除 id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        executionWashingMapper.deleteBatchIds(idList);
    }

    /**
     * @param executionWashing 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(ExecutionWashingReq executionWashing) {
        if (StrUtil.isBlank(executionWashing.getWashingExecutionId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        ExecutionWashing updateObj = new ExecutionWashing();
        BeanUtil.copyProperties(executionWashing, updateObj);
        int updateCount = executionWashingMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public ExecutionWashingVO selectDetailById(String id) {
        ExecutionWashing executionWashing = executionWashingMapper.selectById(id);
        if (executionWashing == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(executionWashing, ExecutionWashingVO.class);
    }

    @Override
    public ExecutionWashingVO selectByDate(String mineCode,String date) {
        ExecutionWashingVO executionWashingVO = executionWashingMapper.selectByDate(mineCode,date);
        return executionWashingVO;
    }
}
